
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>编写自定义 django-admin 命令 &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="编写自定义模型字段(model fields)" href="custom-model-fields.html" />
    <link rel="prev" title="使用 REMOTE_USER 进行身份验证" href="auth-remote-user.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="auth-remote-user.html" title="使用 &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;REMOTE_USER&lt;/span&gt;&lt;/code&gt; 进行身份验证">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="custom-model-fields.html" title="编写自定义模型字段(model fields)">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-custom-management-commands">
            
  <div class="section" id="s-module-django.core.management">
<span id="s-writing-custom-django-admin-commands"></span><span id="module-django.core.management"></span><span id="writing-custom-django-admin-commands"></span><h1>编写自定义 <code class="docutils literal notranslate"><span class="pre">django-admin</span></code> 命令<a class="headerlink" href="#module-django.core.management" title="永久链接至标题">¶</a></h1>
<p>应用程序可以用 <code class="docutils literal notranslate"><span class="pre">manage.py</span></code> 注册自己的动作。例如，你可能想为你正在分发的 Django 应用添加一个 <code class="docutils literal notranslate"><span class="pre">manage.py</span></code> 动作。在本文档中，我们将为 <a class="reference internal" href="../intro/tutorial01.html"><span class="doc">教程</span></a> 中的 <code class="docutils literal notranslate"><span class="pre">polls</span></code> 应用程序构建一个自定义的 <code class="docutils literal notranslate"><span class="pre">closepoll</span></code> 命令。</p>
<p>要做到这一点，在应用程序中添加一个 <code class="docutils literal notranslate"><span class="pre">management/commands</span></code> 目录。Django 会给目录下的每个 Python 模块注册一个 <code class="docutils literal notranslate"><span class="pre">manage.py</span></code> 命令，这个命令的名字不以下划线开头。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">polls</span><span class="o">/</span>
    <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
    <span class="n">models</span><span class="o">.</span><span class="n">py</span>
    <span class="n">management</span><span class="o">/</span>
        <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
        <span class="n">commands</span><span class="o">/</span>
            <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
            <span class="n">_private</span><span class="o">.</span><span class="n">py</span>
            <span class="n">closepoll</span><span class="o">.</span><span class="n">py</span>
    <span class="n">tests</span><span class="o">.</span><span class="n">py</span>
    <span class="n">views</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>在这个例子中，<code class="docutils literal notranslate"><span class="pre">closepoll</span></code> 命令将提供给任何在 <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 中包含 <code class="docutils literal notranslate"><span class="pre">polls</span></code> 应用程序的项目。</p>
<p><code class="docutils literal notranslate"><span class="pre">_private.py</span></code> 模块将不会作为管理命令使用。</p>
<p><code class="docutils literal notranslate"><span class="pre">closepoll.py</span></code> 模块只有一个要求——必须定义 <code class="docutils literal notranslate"><span class="pre">Command</span></code> 类，该类继承自 <a class="reference internal" href="#django.core.management.BaseCommand" title="django.core.management.BaseCommand"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCommand</span></code></a> 或其 <a class="reference internal" href="#ref-basecommand-subclasses"><span class="std std-ref">子类</span></a>。</p>
<div class="admonition-standalone-scripts admonition">
<p class="first admonition-title">独立的脚本</p>
<p class="last">自定义管理命令在运行独立脚本命令方面十分有用，也可用于 UNIX 的周期性 crontab 任务，或是 Windows 的定时任务。</p>
</div>
<p>要实现该命令，请编辑 <code class="docutils literal notranslate"><span class="pre">polls/management/commands/closepoll.py</span></code> 如下：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.management.base</span> <span class="kn">import</span> <span class="n">BaseCommand</span><span class="p">,</span> <span class="n">CommandError</span>
<span class="kn">from</span> <span class="nn">polls.models</span> <span class="kn">import</span> <span class="n">Question</span> <span class="k">as</span> <span class="n">Poll</span>

<span class="k">class</span> <span class="nc">Command</span><span class="p">(</span><span class="n">BaseCommand</span><span class="p">):</span>
    <span class="n">help</span> <span class="o">=</span> <span class="s1">&#39;Closes the specified poll for voting&#39;</span>

    <span class="k">def</span> <span class="nf">add_arguments</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;poll_ids&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">options</span><span class="p">):</span>
        <span class="k">for</span> <span class="n">poll_id</span> <span class="ow">in</span> <span class="n">options</span><span class="p">[</span><span class="s1">&#39;poll_ids&#39;</span><span class="p">]:</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">poll</span> <span class="o">=</span> <span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">poll_id</span><span class="p">)</span>
            <span class="k">except</span> <span class="n">Poll</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
                <span class="k">raise</span> <span class="n">CommandError</span><span class="p">(</span><span class="s1">&#39;Poll &quot;</span><span class="si">%s</span><span class="s1">&quot; does not exist&#39;</span> <span class="o">%</span> <span class="n">poll_id</span><span class="p">)</span>

            <span class="n">poll</span><span class="o">.</span><span class="n">opened</span> <span class="o">=</span> <span class="kc">False</span>
            <span class="n">poll</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>

            <span class="bp">self</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">style</span><span class="o">.</span><span class="n">SUCCESS</span><span class="p">(</span><span class="s1">&#39;Successfully closed poll &quot;</span><span class="si">%s</span><span class="s1">&quot;&#39;</span> <span class="o">%</span> <span class="n">poll_id</span><span class="p">))</span>
</pre></div>
</div>
<div class="admonition note" id="management-commands-output">
<p class="first admonition-title">注解</p>
<p>当你使用管理命令并希望提供控制台输出时，你需要 write 至 <code class="docutils literal notranslate"><span class="pre">self.stdout</span></code> 和 <code class="docutils literal notranslate"><span class="pre">self.stderr</span></code>，而不是直接 print 至 <code class="docutils literal notranslate"><span class="pre">stdout</span></code> 和 <code class="docutils literal notranslate"><span class="pre">stderr</span></code>。利用这些代理，测试自定义命令会更方便。还需要注意的是，你不需要用换行符来结束消息，它会自动添加，除非你指定了 <code class="docutils literal notranslate"><span class="pre">ending</span></code> 参数：</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Unterminated line&quot;</span><span class="p">,</span> <span class="n">ending</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<p>这个新的自定义命令能用 <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">closepoll</span> <span class="pre">&lt;poll_ids&gt;</span></code> 调用。</p>
<p><code class="docutils literal notranslate"><span class="pre">handle()</span></code> 方法接受一个或多个 <code class="docutils literal notranslate"><span class="pre">poll_ids</span></code>，并将每个 <code class="docutils literal notranslate"><span class="pre">poll.opened</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。若用户传入了不存在的 polls，将会抛出 <a class="reference internal" href="#django.core.management.CommandError" title="django.core.management.CommandError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CommandError</span></code></a>。<a class="reference internal" href="../intro/tutorial02.html"><span class="doc">教程</span></a> 中不存在 <code class="docutils literal notranslate"><span class="pre">poll.opened</span></code> 属性，只是这里为了本例添加至 <code class="docutils literal notranslate"><span class="pre">polls.models.Question</span></code> 的。</p>
<div class="section" id="s-accepting-optional-arguments">
<span id="s-custom-commands-options"></span><span id="accepting-optional-arguments"></span><span id="custom-commands-options"></span><h2>接受可选参数<a class="headerlink" href="#accepting-optional-arguments" title="永久链接至标题">¶</a></h2>
<p>同样的 <code class="docutils literal notranslate"><span class="pre">closepoll</span></code> 可以很容易地修改，通过接受额外的命令行选项来删除一个给定的投票，而不是关闭它。这些自定义选项可以在 <a class="reference internal" href="#django.core.management.BaseCommand.add_arguments" title="django.core.management.BaseCommand.add_arguments"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_arguments()</span></code></a> 方法中添加，比如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Command</span><span class="p">(</span><span class="n">BaseCommand</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">add_arguments</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
        <span class="c1"># Positional arguments</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;poll_ids&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>

        <span class="c1"># Named (optional) arguments</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
            <span class="s1">&#39;--delete&#39;</span><span class="p">,</span>
            <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">,</span>
            <span class="n">help</span><span class="o">=</span><span class="s1">&#39;Delete poll instead of closing it&#39;</span><span class="p">,</span>
        <span class="p">)</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">options</span><span class="p">):</span>
        <span class="c1"># ...</span>
        <span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="s1">&#39;delete&#39;</span><span class="p">]:</span>
            <span class="n">poll</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
        <span class="c1"># ...</span>
</pre></div>
</div>
<p>选项（本例中 <code class="docutils literal notranslate"><span class="pre">delete</span></code>）是由 handle 方法的 options 字典参数传入的。参见 Python 文档查询 <a class="reference external" href="https://docs.python.org/3/library/argparse.html#module-argparse" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>，获取更多 <code class="docutils literal notranslate"><span class="pre">add_argument</span></code> 的用法。</p>
<p>为了能添加自定义命令选项，所以的 <a class="reference internal" href="../ref/django-admin.html"><span class="doc">管理命令</span></a> 都能接受一些默认选项，例如 <a class="reference internal" href="../ref/django-admin.html#cmdoption-verbosity"><code class="xref std std-option docutils literal notranslate"><span class="pre">--verbosity</span></code></a> 和 <a class="reference internal" href="../ref/django-admin.html#cmdoption-traceback"><code class="xref std std-option docutils literal notranslate"><span class="pre">--traceback</span></code></a>。</p>
</div>
<div class="section" id="s-management-commands-and-locales">
<span id="s-id1"></span><span id="management-commands-and-locales"></span><span id="id1"></span><h2>管理命令和本地化<a class="headerlink" href="#management-commands-and-locales" title="永久链接至标题">¶</a></h2>
<p>默认情况下，管理命令以当前活动的 locale 执行。</p>
<p>如果由于某些原因，你的自定义管理命令必须在没有活动的 locale 的情况下运行（例如，为了防止翻译的内容被插入数据库），请在你的 <a class="reference internal" href="#django.core.management.BaseCommand.handle" title="django.core.management.BaseCommand.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> 方法上使用 <code class="docutils literal notranslate"><span class="pre">&#64;no_translations</span></code> 装饰器停用翻译：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.management.base</span> <span class="kn">import</span> <span class="n">BaseCommand</span><span class="p">,</span> <span class="n">no_translations</span>

<span class="k">class</span> <span class="nc">Command</span><span class="p">(</span><span class="n">BaseCommand</span><span class="p">):</span>
    <span class="o">...</span>

    <span class="nd">@no_translations</span>
    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">options</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>由于禁用翻译需要使用配置文件，故装饰器不能用于那些不加载配置文件的命令。</p>
</div>
<div class="section" id="s-testing">
<span id="testing"></span><h2>测试<a class="headerlink" href="#testing" title="永久链接至标题">¶</a></h2>
<p>关于如何测试自定义管理命令的内容可在 <a class="reference internal" href="../topics/testing/tools.html#topics-testing-management-commands"><span class="std std-ref">测试文档</span></a> 中找到。</p>
</div>
<div class="section" id="s-overriding-commands">
<span id="overriding-commands"></span><h2>覆盖命令<a class="headerlink" href="#overriding-commands" title="永久链接至标题">¶</a></h2>
<p>Django 先注册内置命令，然后按相反的顺序在 <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 查找命令。在查找时，如果一个命令和已注册的命令重名，这个新发现的命令会覆盖第一个命令。</p>
<p>换句话说，为了覆盖一个命令，新命令必须有同样的名字并且它的 app 在 <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 中必须排在被覆盖命令 app 的前面。</p>
<p>第三方应用提供的管理命令若被不小心重写，能通过在你项目中的某个应用（在 <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 配置在第三方应用之前）创建新命令的方式为其取个别名，另其能被调用。这个应用需要导入被重写的 <code class="docutils literal notranslate"><span class="pre">Command</span></code>。</p>
</div>
<div class="section" id="s-command-objects">
<span id="command-objects"></span><h2>命令对象<a class="headerlink" href="#command-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.core.management.BaseCommand">
<em class="property">class </em><code class="descname">BaseCommand</code><a class="headerlink" href="#django.core.management.BaseCommand" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>所有管理命令最终派生的基类。</p>
<p>如果你想处理解析命令行参数，决定调用什么代码的过程，使用这个类。如果你不需要改变任何行为，考虑直接使用它的某个 <a class="reference internal" href="#ref-basecommand-subclasses"><span class="std std-ref">子类</span></a>。</p>
<p>继承 <a class="reference internal" href="#django.core.management.BaseCommand" title="django.core.management.BaseCommand"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCommand</span></code></a> 要求你重写 <a class="reference internal" href="#django.core.management.BaseCommand.handle" title="django.core.management.BaseCommand.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> 方法。</p>
<div class="section" id="s-attributes">
<span id="attributes"></span><h3>属性<a class="headerlink" href="#attributes" title="永久链接至标题">¶</a></h3>
<p>能被你派生的子类设置的，且能被 <a class="reference internal" href="#django.core.management.BaseCommand" title="django.core.management.BaseCommand"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCommand</span></code></a> 的 <a class="reference internal" href="#ref-basecommand-subclasses"><span class="std std-ref">子类</span></a> 使用的属性。</p>
<dl class="attribute">
<dt id="django.core.management.BaseCommand.help">
<code class="descclassname">BaseCommand.</code><code class="descname">help</code><a class="headerlink" href="#django.core.management.BaseCommand.help" title="永久链接至目标">¶</a></dt>
<dd><p>命令简介，当用户运行命令 <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">help</span> <span class="pre">&lt;command&gt;</span></code> 时包含在打印的帮助信息内。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.core.management.BaseCommand.missing_args_message">
<code class="descclassname">BaseCommand.</code><code class="descname">missing_args_message</code><a class="headerlink" href="#django.core.management.BaseCommand.missing_args_message" title="永久链接至目标">¶</a></dt>
<dd><p>如果你的命令定义了必须的位置参数，你可以在缺失参数时返回自定义错误消息。默认输出由 <a class="reference external" href="https://docs.python.org/3/library/argparse.html#module-argparse" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 打印(&quot;too few arguments&quot;)。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.core.management.BaseCommand.output_transaction">
<code class="descclassname">BaseCommand.</code><code class="descname">output_transaction</code><a class="headerlink" href="#django.core.management.BaseCommand.output_transaction" title="永久链接至目标">¶</a></dt>
<dd><p>一个布尔值，决定命令是否暑输出 SQL 语句；若为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，输出内容会自动以 <code class="docutils literal notranslate"><span class="pre">BEGIN;</span></code> 和 <code class="docutils literal notranslate"><span class="pre">COMMIT;</span></code> 包裹。默认值为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.core.management.BaseCommand.requires_migrations_checks">
<code class="descclassname">BaseCommand.</code><code class="descname">requires_migrations_checks</code><a class="headerlink" href="#django.core.management.BaseCommand.requires_migrations_checks" title="永久链接至目标">¶</a></dt>
<dd><p>一个布尔值；若为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，命令会在硬盘上存储的 migrations 与 数据库中的不一致时打印警告。警告不会阻止命令执行。默认值为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.core.management.BaseCommand.requires_system_checks">
<code class="descclassname">BaseCommand.</code><code class="descname">requires_system_checks</code><a class="headerlink" href="#django.core.management.BaseCommand.requires_system_checks" title="永久链接至目标">¶</a></dt>
<dd><p>A list or tuple of tags, e.g. <code class="docutils literal notranslate"><span class="pre">[Tags.staticfiles,</span> <span class="pre">Tags.models]</span></code>. System
checks <a class="reference internal" href="../topics/checks.html#registering-labeling-checks"><span class="std std-ref">registered in the chosen tags</span></a>
will be checked for errors prior to executing the command. The value
<code class="docutils literal notranslate"><span class="pre">'__all__'</span></code> can be used to specify that all system checks should be
performed. Default value is <code class="docutils literal notranslate"><span class="pre">'__all__'</span></code>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>In older versions, the <code class="docutils literal notranslate"><span class="pre">requires_system_checks</span></code> attribute expects a
boolean value instead of a list or tuple of tags.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.core.management.BaseCommand.style">
<code class="descclassname">BaseCommand.</code><code class="descname">style</code><a class="headerlink" href="#django.core.management.BaseCommand.style" title="永久链接至目标">¶</a></dt>
<dd><p>一个实例属性，用于向 <code class="docutils literal notranslate"><span class="pre">stdout</span></code> 或 <code class="docutils literal notranslate"><span class="pre">stderr</span></code> 输出彩色内容。例如:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">style</span><span class="o">.</span><span class="n">SUCCESS</span><span class="p">(</span><span class="s1">&#39;...&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>参考 <a class="reference internal" href="../ref/django-admin.html#syntax-coloring"><span class="std std-ref">语法着色</span></a> 了解如何修改调色板与现成的样式（使用本节介绍的大写字母版本的 &quot;roles&quot;）。</p>
<p>如果运行命令时传递了 <a class="reference internal" href="../ref/django-admin.html#cmdoption-no-color"><code class="xref std std-option docutils literal notranslate"><span class="pre">--no-color</span></code></a> 选项，所有的 <code class="docutils literal notranslate"><span class="pre">self.style()</span></code> 调用会返回未染色的原始字符串。</p>
</dd></dl>

</div>
<div class="section" id="s-methods">
<span id="methods"></span><h3>方法<a class="headerlink" href="#methods" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#django.core.management.BaseCommand" title="django.core.management.BaseCommand"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCommand</span></code></a> 有很多方法可供重写，不过仅有 <a class="reference internal" href="#django.core.management.BaseCommand.handle" title="django.core.management.BaseCommand.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> 是必须实现的。</p>
<div class="admonition-implementing-a-constructor-in-a-subclass admonition">
<p class="first admonition-title">子类中实现构造器</p>
<p>若 <a class="reference internal" href="#django.core.management.BaseCommand" title="django.core.management.BaseCommand"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCommand</span></code></a> 的子类实现了 <code class="docutils literal notranslate"><span class="pre">__init__</span></code> 方法，那么就必须调用 <a class="reference internal" href="#django.core.management.BaseCommand" title="django.core.management.BaseCommand"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCommand</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">__init__</span></code>:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Command</span><span class="p">(</span><span class="n">BaseCommand</span><span class="p">):</span>
    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="c1"># ...</span>
</pre></div>
</div>
</div>
<dl class="method">
<dt id="django.core.management.BaseCommand.create_parser">
<code class="descclassname">BaseCommand.</code><code class="descname">create_parser</code>(<em>prog_name</em>, <em>subcommand</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.core.management.BaseCommand.create_parser" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个 <code class="docutils literal notranslate"><span class="pre">CommandParser</span></code> 实例，它是 <a class="reference external" href="https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 的子类，包含一些针对 Django 的个性化设计。</p>
<p>你可以自定义这个实例，通过重写此方法，并为  <code class="docutils literal notranslate"><span class="pre">super()</span></code> 方法传入值为 <a class="reference external" href="https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> 参数。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.management.BaseCommand.add_arguments">
<code class="descclassname">BaseCommand.</code><code class="descname">add_arguments</code>(<em>parser</em>)<a class="headerlink" href="#django.core.management.BaseCommand.add_arguments" title="永久链接至目标">¶</a></dt>
<dd><p>添加命令行转换参数的入口，用于处理传给命令行的参数。自定义命令需要重写此方法，并同时添加命令接受的位置参数和可选参数。直接使用 <code class="docutils literal notranslate"><span class="pre">BaseCommand</span></code> 的子类时无需调用 <code class="docutils literal notranslate"><span class="pre">super()</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.management.BaseCommand.get_version">
<code class="descclassname">BaseCommand.</code><code class="descname">get_version</code>()<a class="headerlink" href="#django.core.management.BaseCommand.get_version" title="永久链接至目标">¶</a></dt>
<dd><p>返回 Django 版本，内置 Django 命令必须正确返回。用户实现的命令可以重写此方法返回自己的版本。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.management.BaseCommand.execute">
<code class="descclassname">BaseCommand.</code><code class="descname">execute</code>(<em>*args</em>, <em>**options</em>)<a class="headerlink" href="#django.core.management.BaseCommand.execute" title="永久链接至目标">¶</a></dt>
<dd><p>试着执行此命令，如果需要的话，进行系统检查（由 <a class="reference internal" href="#django.core.management.BaseCommand.requires_system_checks" title="django.core.management.BaseCommand.requires_system_checks"><code class="xref py py-attr docutils literal notranslate"><span class="pre">requires_system_checks</span></code></a> 控制）。若命令抛出 <a class="reference internal" href="#django.core.management.CommandError" title="django.core.management.CommandError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CommandError</span></code></a>，这会导致命令中断，并将错误输出至 stderr。</p>
</dd></dl>

<div class="admonition-calling-a-management-command-in-your-code admonition">
<p class="first admonition-title">在你的代码中调用管理命令</p>
<p class="last">执行命令时，不要从代码直接调用 <code class="docutils literal notranslate"><span class="pre">execute()</span></code> 方法。而是使用 <a class="reference internal" href="../ref/django-admin.html#django.core.management.call_command" title="django.core.management.call_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">call_command()</span></code></a>。</p>
</div>
<dl class="method">
<dt id="django.core.management.BaseCommand.handle">
<code class="descclassname">BaseCommand.</code><code class="descname">handle</code>(<em>*args</em>, <em>**options</em>)<a class="headerlink" href="#django.core.management.BaseCommand.handle" title="永久链接至目标">¶</a></dt>
<dd><p>命令的实际逻辑处理。子类必须实现此方法。</p>
<p>此方法可能会返回一个字符串，输出至 <code class="docutils literal notranslate"><span class="pre">stdout</span></code> （若 <a class="reference internal" href="#django.core.management.BaseCommand.output_transaction" title="django.core.management.BaseCommand.output_transaction"><code class="xref py py-attr docutils literal notranslate"><span class="pre">output_transaction</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，则由 <code class="docutils literal notranslate"><span class="pre">BEGIN;</span></code> 和 <code class="docutils literal notranslate"><span class="pre">COMMIT</span></code> 包裹）。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.management.BaseCommand.check">
<code class="descclassname">BaseCommand.</code><code class="descname">check</code>(<em>app_configs=None</em>, <em>tags=None</em>, <em>display_num_errors=False</em>)<a class="headerlink" href="#django.core.management.BaseCommand.check" title="永久链接至目标">¶</a></dt>
<dd><p>利用系统检查框架校验 Django 项目是否存在隐含的问题。严重的问题会抛出 <a class="reference internal" href="#django.core.management.CommandError" title="django.core.management.CommandError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CommandError</span></code></a>；警告会输出至 stderr；次要通知输出至 stdout。</p>
<p>若 <code class="docutils literal notranslate"><span class="pre">app_configs</span></code> 和 <code class="docutils literal notranslate"><span class="pre">tags</span></code> 均为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，所以的系统检查项都会被运行。<code class="docutils literal notranslate"><span class="pre">tags</span></code> 能是一个检查标签的列表，例如 <code class="docutils literal notranslate"><span class="pre">compatibility</span></code> 或 <code class="docutils literal notranslate"><span class="pre">models</span></code>。</p>
</dd></dl>

</div>
<div class="section" id="s-basecommand-subclasses">
<span id="s-ref-basecommand-subclasses"></span><span id="basecommand-subclasses"></span><span id="ref-basecommand-subclasses"></span><h3><code class="docutils literal notranslate"><span class="pre">BaseCommand</span></code> 的子类<a class="headerlink" href="#basecommand-subclasses" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.core.management.AppCommand">
<em class="property">class </em><code class="descname">AppCommand</code><a class="headerlink" href="#django.core.management.AppCommand" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>管理命令接受一个或多个应用标签参数，并对每项应用做某些事。</p>
<p>子类必须实现 <a class="reference internal" href="#django.core.management.AppCommand.handle_app_config" title="django.core.management.AppCommand.handle_app_config"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_app_config()</span></code></a>，而不是 <a class="reference internal" href="#django.core.management.BaseCommand.handle" title="django.core.management.BaseCommand.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a>。此方法会为每个应用调用一次。</p>
<dl class="method">
<dt id="django.core.management.AppCommand.handle_app_config">
<code class="descclassname">AppCommand.</code><code class="descname">handle_app_config</code>(<em>app_config</em>, <em>**options</em>)<a class="headerlink" href="#django.core.management.AppCommand.handle_app_config" title="永久链接至目标">¶</a></dt>
<dd><p>为 <code class="docutils literal notranslate"><span class="pre">app_config</span></code> 运行命令，这会是 <a class="reference internal" href="../ref/applications.html#django.apps.AppConfig" title="django.apps.AppConfig"><code class="xref py py-class docutils literal notranslate"><span class="pre">AppConfig</span></code></a> 的实例，并指向命令行给定的应用标签。</p>
</dd></dl>

<dl class="class">
<dt id="django.core.management.LabelCommand">
<em class="property">class </em><code class="descname">LabelCommand</code><a class="headerlink" href="#django.core.management.LabelCommand" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个管理命令，从命令行接受一个或任意多个参数(labels)，并针对每项做些事情。</p>
<p>子类必须实现 <a class="reference internal" href="#django.core.management.LabelCommand.handle_label" title="django.core.management.LabelCommand.handle_label"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_label()</span></code></a>，而不是 <a class="reference internal" href="#django.core.management.BaseCommand.handle" title="django.core.management.BaseCommand.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a>。此方法会为每个应用调用一次。</p>
<dl class="attribute">
<dt id="django.core.management.LabelCommand.label">
<code class="descclassname">LabelCommand.</code><code class="descname">label</code><a class="headerlink" href="#django.core.management.LabelCommand.label" title="永久链接至目标">¶</a></dt>
<dd><p>一个字符串，介绍了传递给命令的任意多个参数。此字符串用于命令的用法文本和错误消息。默认为 <code class="docutils literal notranslate"><span class="pre">'label'</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.management.LabelCommand.handle_label">
<code class="descclassname">LabelCommand.</code><code class="descname">handle_label</code>(<em>label</em>, <em>**options</em>)<a class="headerlink" href="#django.core.management.LabelCommand.handle_label" title="永久链接至目标">¶</a></dt>
<dd><p>运行 <code class="docutils literal notranslate"><span class="pre">label</span></code> 指定的命令动作，由命令行传入的字符串指定。</p>
</dd></dl>

</div>
<div class="section" id="s-command-exceptions">
<span id="command-exceptions"></span><h3>命令异常<a class="headerlink" href="#command-exceptions" title="永久链接至标题">¶</a></h3>
<dl class="exception">
<dt id="django.core.management.CommandError">
<em class="property">exception </em><code class="descname">CommandError</code>(<em>returncode=1</em>)<a class="headerlink" href="#django.core.management.CommandError" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>异常类说明在运行管理命令时出错了。</p>
<p>在命令行控制台里执行管理命令的过程中，如果抛出了这个异常，该异常将会被捕获并以便于阅读的样子打印到对应的输出流（i.e., stderr）；因此，抛出这个异常（对错误的适当描述）是说明命令执行出错了的首选方式。它接收可选参数 <code class="docutils literal notranslate"><span class="pre">returncode</span></code> 来使用 <a class="reference external" href="https://docs.python.org/3/library/sys.html#sys.exit" title="(在 Python v3.9)"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> 自定义退出管理命令所用的退出状态。</p>
<p>如果管理命令是由 <a class="reference internal" href="../ref/django-admin.html#django.core.management.call_command" title="django.core.management.call_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">call_command()</span></code></a> 调用的，是否捕获异常取决于你。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>新增了 <code class="docutils literal notranslate"><span class="pre">returncode</span></code> 参数。</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">编写自定义 <code class="docutils literal notranslate"><span class="pre">django-admin</span></code> 命令</a><ul>
<li><a class="reference internal" href="#accepting-optional-arguments">接受可选参数</a></li>
<li><a class="reference internal" href="#management-commands-and-locales">管理命令和本地化</a></li>
<li><a class="reference internal" href="#testing">测试</a></li>
<li><a class="reference internal" href="#overriding-commands">覆盖命令</a></li>
<li><a class="reference internal" href="#command-objects">命令对象</a><ul>
<li><a class="reference internal" href="#attributes">属性</a></li>
<li><a class="reference internal" href="#methods">方法</a></li>
<li><a class="reference internal" href="#basecommand-subclasses"><code class="docutils literal notranslate"><span class="pre">BaseCommand</span></code> 的子类</a></li>
<li><a class="reference internal" href="#command-exceptions">命令异常</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="auth-remote-user.html"
                        title="上一章">使用 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 进行身份验证</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="custom-model-fields.html"
                        title="下一章">编写自定义模型字段(model fields)</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/custom-management-commands.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="auth-remote-user.html" title="使用 &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;REMOTE_USER&lt;/span&gt;&lt;/code&gt; 进行身份验证">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="custom-model-fields.html" title="编写自定义模型字段(model fields)">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>